package com.y.mytest.jm.erwema;

public class CRC8 {
    static final byte[] crcTbl;

    static {
        crcTbl = new byte[256];
        byte polynomial = 0x07; // 0x107 less the leading x^8
        for (int i = 0; i < 256; i++) {
            byte j = (byte) i;
            for (int k = 0; k < 8; k++) {
                j = (byte) ((j < 0) ? (j << 1) ^ polynomial : j << 1);
            }
            crcTbl[i] = j;
        }
    }

    // The rest is test code.
    private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    private static String hexString(byte b) {
        return hexDigits[0xf & (b >> 4)] + "" + hexDigits[b & 0xf];
    }

    public static byte crc8(byte[] data) {
        byte crcReg = 0;
        for (byte datum : data) {
            crcReg = crcTbl[(crcReg ^ datum) & 0xFF];
        }
        return crcReg;
    }

    private static void test(byte[] vec) {
        System.out.println(hexString(crc8(vec)));
    }

    public static void main(String[] args) {
        byte[] bytes = "12321SSSDS2A".getBytes();
        test(new byte[]{(byte) 'T'}); // 0xab
        test(bytes); // 0xab
        test(new byte[]{(byte) '1', (byte) '2', (byte) '3', (byte) '2', (byte) '1', (byte) 'S', (byte) 'S', (byte) 'S', (byte) 'D', (byte) 'S', (byte) '2', (byte) 'A'}); // 0xab
        test(new byte[]{(byte) 0x03, (byte) 0x73}); // 0x61
        test(new byte[]{(byte) 0x01, (byte) 0x3f}); // 0xa8

    }

} 